package com.dianrui.agent.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Process;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.dianrui.agent.Constant;
import com.dianrui.agent.R;
import com.dianrui.agent.event.SwitchOrderEvent;
import com.dianrui.agent.fragment.FragmentMainMy;
import com.dianrui.agent.fragment.FragmentMainOrder;
import com.dianrui.agent.fragment.FragmentMainWork;
import com.dianrui.agent.util.MyUtil;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.google.gson.JsonObject;


import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


public class MainActivity extends BaseActivity {

    private long mclicktime;


    FragmentMainOrder fragmentOrder;
    FragmentMainWork fragmentWorkTable;
    FragmentMainMy fragmentMy;
    @BindView(R.id.act_main_container)
    FrameLayout actMainContainer;
    @BindView(R.id.divide)
    View divide;
    @BindView(R.id.act_main_radio_work)
    RadioButton actMainRadioWork;
    @BindView(R.id.act_main_radio_order)
    RadioButton actMainRadioOrder;
    @BindView(R.id.act_main_rb_my)
    RadioButton actMainRbMy;
    @BindView(R.id.act_main_group_radioGroup)
    RadioGroup actMainGroupRadioGroup;
    private RadioButton[] button_radios;
    private int lastShowFragment = 0;//上一个选中Fragment或RadioButton的下标
    private long clicktime;




    @Override
    public int getContentViewId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        setTarget();
        button_radios = new RadioButton[]{actMainRadioWork,
                actMainRadioOrder, actMainRbMy};

        Drawable drawable_work = getResources().getDrawable(R.drawable.main_tab_home_worktable);
        drawable_work.setBounds(0, 0, 60, 60);
        actMainRadioWork.setCompoundDrawables(null, drawable_work, null, null);

        Drawable drawable_order = getResources().getDrawable(R.drawable.main_tab_home_order);
        //当这个图片被绘制时，给他绑定一个矩形 ltrb规定这个矩形
        drawable_order.setBounds(0, 0, 60, 60);
        actMainRadioOrder.setCompoundDrawables(null, drawable_order, null, null);


        Drawable drawable_my = getResources().getDrawable(R.drawable.main_tab_home_my);
        //当这个图片被绘制时，给他绑定一个矩形 ltrb规定这个矩形
        drawable_my.setBounds(0, 0, 60, 60);
        actMainRbMy.setCompoundDrawables(null, drawable_my, null, null);


        changePage(0);

        loginAgain();

    }





    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(SwitchOrderEvent switchOrderEvent) {
        changePage(1);
    }

    private void changePage(int position) {
        if (button_radios != null) {
            button_radios[lastShowFragment].setChecked(false);
        }

        if (button_radios != null) {
            for (int i = 0; i < button_radios.length; i++) {
                button_radios[i].setChecked(false);
            }
        }


        button_radios[position].setChecked(true);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        hideFragments(transaction);

        switch (position) {
            case 0:
                if (fragmentWorkTable == null) {
                    fragmentWorkTable = new FragmentMainWork();
                    transaction.add(R.id.act_main_container, fragmentWorkTable);
                } else {
                    transaction.show(fragmentWorkTable);
                }

                break;
            case 1:

                if (fragmentOrder == null) {
                    fragmentOrder = new FragmentMainOrder();
                    transaction.add(R.id.act_main_container, fragmentOrder);
                } else {
                    transaction.show(fragmentOrder);
                }
                break;

            case 2:
                if (fragmentMy == null) {
                    fragmentMy = new FragmentMainMy();
                    transaction.add(R.id.act_main_container, fragmentMy);
                } else {
                    transaction.show(fragmentMy);
                }
                break;

            default:
                break;
        }
        transaction.commitAllowingStateLoss();
        lastShowFragment = position;
    }


    private void hideFragments(FragmentTransaction transaction) {

        if (fragmentWorkTable != null) {
            transaction.hide(fragmentWorkTable);
        }

        if (fragmentOrder != null) {
            transaction.hide(fragmentOrder);
        }
        if (fragmentMy != null) {
            transaction.hide(fragmentMy);
        }

    }

    /**
     * 首次运行弹出协议和隐私对话框判断
     **/
    private void setTarget() {
        SharedPreferences share = getSharedPreferences("FirstInfo", MODE_PRIVATE);
        SharedPreferences.Editor editor = share.edit();
        editor.putBoolean("isFirstIn", false);
        editor.apply();
    }

    private void loginAgain() {
        JsonObject loginJson = new JsonObject();
        loginJson.addProperty("device_number", MyUtil.getUniqueId(MainActivity.this));
        OkHttpRequest.getInstance().postLoginTokenRequests(SharedUtil.getUrl() + Url.AGAIN_LOGIN, loginJson.toString(), new OkHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject && !isFinishing()) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                spUtils.put("account", jsonObject.optJSONObject("data").optString("account"));
                                spUtils.put("nickname", jsonObject.optJSONObject("data").optString("nickname"));
                                spUtils.put("mobile", jsonObject.optJSONObject("data").optString("mobile"));
                                spUtils.put("email", jsonObject.optJSONObject("data").optString("email"));
                                spUtils.put("alias", jsonObject.optJSONObject("data").optString("alias"));
                                spUtils.put("scan_url", jsonObject.optJSONObject("data").optString("scan_url"));
                                spUtils.put("menu", String.valueOf(result));
                                SharedUtil.setToken(jsonObject.optJSONObject("data").optString("token"));
                            }else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });

    }


    @OnClick({R.id.act_main_radio_work, R.id.act_main_radio_order, R.id.act_main_rb_my})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.act_main_radio_work:
                changePage(0);
                break;
            case R.id.act_main_radio_order:
                changePage(1);
                break;
            case R.id.act_main_rb_my:
                changePage(2);
                break;

            default:
                break;
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - mclicktime < Constant.CLICKTIME) {
                this.finish();
                MyUtil.getInstance().clear();
                Process.killProcess(Process.myPid());
                System.exit(0);
            } else {
                ToastUtil.showToast(getString(R.string.press_exit));
                mclicktime = System.currentTimeMillis();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
